var express = require('express');
var router = express.Router();

var connection = require('../util/mysqlConfig')

/* GET users listing. */
router.get('/', function(req, res, next) {
  try{
  connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
      if (error) throw error;
      res.json({data:results[0].solution})
      console.log('The solution is: ', results[0].solution);
  })
  }catch(err){
    console.log(err)
  }
});

//创建房间
router.post('/createRooms',function(req,res,next){
    var sql = `insert into rooms values (${null},'${req.body.roomName}','${req.body.roomMaster}')`
    connection.query(sql,function(err,result,fields){
      if(err) throw err;
      console.log(result)
    })
  res.json({message:'ok'})
})



//查询所有房间
router.post('/commonRooms',function(req,res,next){
  connection.getConnection((err,connect)=>{
    var sql = `select * from rooms`
    connect.query(sql,function(err,result,fields){
      if(err) throw err;
      res.json({message:'ok',data:result})
      connect.release()
    })
  })

})

// 查询个人创建的房间列表

router.post('/personRooms',function(req,res,next){
  connection.getConnection((err,connect)=>{
  if(!req.body.admin){
    res.json({
      status:'fail',
      message:'请先登录'
    })
  }else{
    connection.getConnection(function(err,connect){
      var sql = `select * from rooms where roomMaster='${req.body.admin}'`
      connect.query(sql,function(err,result,fields){
        connect.release()
        if(err) throw err;
        res.json({message:'ok',data:result})
      })
    })
  }
  })
})

/**
 * 查询好友列表信息
 */
router.post('/inquireFriendList',function(req,res,next){
  connection.getConnection((err,connect)=>{
    let sql = `select * from users inner join (select friendListId from userinfo inner join users where users.admin = ${req.body.admin}) as listId where users.userId in listId.friendListId`;
    connect.query(sql, function(err,result,fields){
      connect.release()
      if(err) throw err;
      if(req.body.inquire == 'friendList'){
        //返回好友列表id
        res.json({
          status:'success',
          data:result
        })
      }else if(req.body.inquire == 'friendInfo'){
        //返回列表信息
        res.json({
          status:'success',
          userInfos:{
            admin:result[0].admin,
            email:result[0].email
          }
        })
      }else{
        res.json({
          status:'fail'
        })
      }
      
    })
  })
})

router.post('/inquireUserInfo',function(req,res,next){
    console.log(req.body)
    connection.getConnection((err,connect)=>{
        let sql = ` select * from users inner join userinfo where users.email = ${req.body.email}`;
        connect.query(sql, function(err,result,fields){
          connect.release()
          if(err) throw err;
          res.json({
              userInfos:result
          })
        })
      })
})

module.exports = router;
